import axios from "axios";
import { Loading, Message } from 'element-ui';

let loadings = null;
const instance = axios.create({
  baseURL: '/api/',
  timeout: 30000 //设置 超时
});
instance.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  loadings = Loading.service({ fullscreen: true, background: "rgba(0,0,0,.01)" });
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
instance.interceptors.response.use((response) => {
  // 对响应数据做点什么
  loadings.close();

  if (Object.prototype.hasOwnProperty.call(response.data, "ok")) {
    if (!response.data.ok) {
      Message({
        showClose: true,
        message: response.data.message,
        type: 'error'
      });
      // if("请先登录"==response.data.message){
      //   router.push("/login.html");
      // }
    }
  }

  return response;
}, (error) => {
  // 对响应错误做点什么
  loadings.close();
  Message({
    showClose: true,
    message: error.message,
    type: 'error'
  });
  return Promise.reject(error);
});

/**
* 格式化参数
* @param {String|Array|Object|HTMLFormElement|FormData|URLSearchParams} param
* @return {URLSearchParams}
*/
instance.params = function (param) {
  if (param == null || param == "") {
    return new URLSearchParams();
  }
  if (param.constructor == Array) {
    let param1 = new URLSearchParams();
    for (let obj of param) {
      param1.append(obj.name, obj.value);
    }
    param = param1;
  } else if (param.constructor == Object) {
    let param1 = new URLSearchParams();
    for (let name in param) {
      param1.append(name, param[name]);
    }
    param = param1;
  } else {
    if (param.constructor == HTMLFormElement) {
      param = new FormData(param);
    }
    if (param.constructor == FormData || param.constructor == String) {
      param = new URLSearchParams(param);
    }
  }
  return param;
}
export default instance;